package com.sf.dlb.web.service;

import com.google.gson.internal.LinkedTreeMap;
import com.sf.dlb.bean.ETHWalletRequestBean;
import com.sf.dlb.bean.ETHWalletResponseBean;
import com.sf.dlb.utils.*;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.web.config.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 以太坊钱包API 服务
 * Created by tanjing on 2019/3/5.
 */
@Service
public class ETHWalletService {
    private static Logger logger = LoggerFactory.getLogger(ETHWalletService.class);

    @Resource
    private Global global;
    /**
     * 生成地址接口
     */
    public List generateAddress(){
        logger.info("generateAddress start {}", DateUtils.getDateTime());
        //调用python api
        StringBuffer urlSB=new StringBuffer();
        urlSB.append(global.py_http_api_generate_address).append("?").append("count=").append(global.py_http_api_generate_address_count);
        String url=urlSB.toString();
        Map<String, String> headers=new HashMap<>();
        headers.put("access-token","123456");
        String result= HttpClientUtil.getRequestAndHeader(url,headers);
        ResultVO resultVO= (ResultVO) GsonUtils.getInstance().fromJson(result, ResultVO.class);
        List<ETHWalletResponseBean> responseBeanList=new ArrayList<>();
        if(null!=resultVO&&resultVO.getCode()==200){
            List<Map<String,String>> resultList=(List)resultVO.getData();
            for (Map map:resultList) {
                ETHWalletResponseBean ethWalletResponseBean=new ETHWalletResponseBean();
                ethWalletResponseBean.setAddress((null!=map.get("address")?map.get("address")+"":""));
                ethWalletResponseBean.setPrivateKey((null!=map.get("privateKey")?map.get("privateKey")+"":""));
                ethWalletResponseBean.setPublicKey((null!=map.get("publicKey")?map.get("publicKey")+"":""));
                responseBeanList.add(ethWalletResponseBean);
            }
            logger.info("generateAddress responseBeanList={}",GsonUtils.getInstance().toJson(responseBeanList));
            return responseBeanList;
        }
        logger.info("generateAddress end {}","null");
        return null;
    }
    /**
     * 提现地址验证
     */
    public boolean chckoutExtractAddress(String address){
        logger.info("chckoutExtractAddress start {}",address);
        //调用python api
        StringBuffer urlSB=new StringBuffer();
        urlSB.append(global.py_http_api_address_validation).append("?").append("address=").append(address);
        String url=urlSB.toString();
        Map<String, String> headers=new HashMap<>();
        headers.put("access-token","123456");
        String result= HttpClientUtil.getRequestAndHeader(url,headers);
        ResultVO resultVO= (ResultVO) GsonUtils.getInstance().fromJson(result, ResultVO.class);
        if(null==resultVO){
            logger.info("chckoutExtractAddress resultVO is null 地址不合法");
            return false;
        }
        if(resultVO.getCode()!=200){
            logger.info("chckoutExtractAddress resultVO.getCode()!=200 地址不合法");
            return false;
        }
        logger.info("chckoutExtractAddress end {}","true");
        return true;
    }
    /**
     * 提现接口
     */
    public ETHWalletResponseBean extractETH(ETHWalletRequestBean ethWalletRequestBean){
        logger.info("extractETH start {}",GsonUtils.getInstance().toJson(ethWalletRequestBean));
        //调用python api提现逻辑
        String url=global.py_http_api_extract;
        String json=GsonUtils.getInstance().toJson(ethWalletRequestBean);
        Map<String, String> headers=new HashMap<>();
        headers.put("access-token","123456");
        String result= HttpClientUtil.postFromJsonAndHeader(url,json,headers,70*2*1000);
        ResultVO resultVO= (ResultVO) GsonUtils.getInstance().fromJson(result, ResultVO.class);
        if(null==resultVO){
            logger.info("extractETH resultVO is null 提现失败");
            return null;
        }
        if(resultVO.getCode()==0){
            logger.info("extractETH resultVO.getCode()==0 提现失败");
            return null;
        }
        LinkedTreeMap resuleMap=(LinkedTreeMap)resultVO.getData();
        ETHWalletResponseBean ethWalletResponseBean=new ETHWalletResponseBean();
        ethWalletResponseBean.setResponseCode(resultVO.getCode()+"");
        ethWalletResponseBean.setExtractNumber(resuleMap.get("serialNumber").toString());
        ethWalletResponseBean.setTransactionHash(resuleMap.get("transactionHash").toString());
        ethWalletResponseBean.setUserId(resuleMap.get("userId").toString());
        logger.info("extractETH end {}",GsonUtils.getInstance().toJson(ethWalletResponseBean));
        return ethWalletResponseBean;
    }

    /**
     * 提现记录
     */
    public List extractRecrd(String userId,List<String> walletExtractInfos){
        logger.info("extractRecrd start {}",GsonUtils.getInstance().toJson(walletExtractInfos));
        Map<String,Object> stringObjectMap=new HashMap<>();
        stringObjectMap.put("userId",userId);
        stringObjectMap.put("hashList",walletExtractInfos);
        //调用python api
        String url=global.py_http_api_extract_recrd;
        String json=GsonUtils.getInstance().toJson(stringObjectMap);
        Map<String, String> headers=new HashMap<>();
        headers.put("access-token","123456");
        String result= HttpClientUtil.postFromJsonAndHeader(url,json,headers);
        ResultVO resultVO= (ResultVO) GsonUtils.getInstance().fromJson(result, ResultVO.class);
        if(null!=resultVO&&resultVO.getCode()==200){
            List<String> resultList=new ArrayList<>();
            LinkedTreeMap resultMap=(LinkedTreeMap)resultVO.getData();
            List<LinkedTreeMap> transactionsList= (List<LinkedTreeMap>) resultMap.get("transactionsList");
            for (LinkedTreeMap linkedTreeMap:transactionsList) {
                resultList.add(linkedTreeMap.get("transactionHash")+"");
            }
            logger.info("extractRecrd end {}",GsonUtils.getInstance().toJson(resultList));
            return resultList;
        }
        logger.info("extractRecrd end {}","null");
        return null;
    }
    /**
     * 充值记录
     */
    public List<ETHWalletResponseBean> topUpRecrd(String userAdress){
        logger.info("topUpRecrd start {}",userAdress);
        //调用python api
        StringBuffer urlSB=new StringBuffer();
        urlSB.append(global.py_http_api_topup_recrd).append("?").append("address=").append(userAdress);
        String url=urlSB.toString();
        Map<String, String> headers=new HashMap<>();
        headers.put("access-token","123456");
        String result= HttpClientUtil.getRequestAndHeader(url,headers);
        ResultVO resultVO= (ResultVO) GsonUtils.getInstance().fromJson(result, ResultVO.class);
        List<ETHWalletResponseBean> ethWalletResponseBeans=new ArrayList<>();
        if(null!=resultVO&&resultVO.getCode()==200){
            List<Map<String,String>> resultList=(List)resultVO.getData();
            for (Map map:resultList) {
                ETHWalletResponseBean ethWalletResponseBean=new ETHWalletResponseBean();
                ethWalletResponseBean.setTransactionHash((null!=map.get("transactionHash")?map.get("transactionHash")+"":""));
                ethWalletResponseBean.setFrom((null!=map.get("from")?map.get("from")+"":""));
                ethWalletResponseBean.setTo((null!=map.get("to")?map.get("to")+"":""));
                ethWalletResponseBean.setCount((null!=map.get("count")?map.get("count")+"":""));
                ethWalletResponseBean.setTimestamp((null!=map.get("timestamp")?map.get("timestamp")+"":""));
                ethWalletResponseBeans.add(ethWalletResponseBean);
            }
            logger.info("topUpRecrd end ethWalletResponseBeans={}",GsonUtils.getInstance().toJson(ethWalletResponseBeans));
            return ethWalletResponseBeans;
        }
        logger.info("topUpRecrd end {}","null");
        return null;
    }


}
